package com.eugene.shiftscalendar;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.RemoteViews;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by Eugene on 17.02.14.
 */

public class MainWindow extends AppWidgetProvider {

    public static final boolean EMULATOR = true;

    private static final String ACTION_PREVIOUS_MONTH
            = "com.eugene.android.shiftscalendar.action.PREVIOUS_MONTH";
    private static final String ACTION_NEXT_MONTH
            = "com.eugene.android.shiftscalendar.action.NEXT_MONTH";
    private static final String ACTION_RESET_MONTH
            = "com.eugene.android.shiftscalendar.action.RESET_MONTH";
    private static final String ACTION_DATE_CLICK
            = "com.eugene.android.shiftscalendar.action.DATE_CLICK";
    private static final String ACTION_SETTINGS
            = "com.eugene.android.shiftscalendar.action.SETTINGS";
    public static final String ACTION_UPDATE
            = "com.eugene.android.shiftscalendar.action.APPWIDGET_UPDATE";

    WidgetSizes _sizes = new WidgetSizes();
    BasePainter _painter = new GlassPainter(_sizes);

    int daysId[] = {R.id.day1, R.id.day2, R.id.day3, R.id.day4, R.id.day5, R.id.day6, R.id.day7,
            R.id.day8, R.id.day9, R.id.day10, R.id.day11, R.id.day12, R.id.day13, R.id.day14,
            R.id.day15, R.id.day16, R.id.day17, R.id.day18, R.id.day19, R.id.day20, R.id.day21,
            R.id.day22, R.id.day23, R.id.day24, R.id.day25, R.id.day26, R.id.day27, R.id.day28,
            R.id.day29, R.id.day30, R.id.day31, R.id.day32, R.id.day33, R.id.day34, R.id.day35,
            R.id.day36, R.id.day37, R.id.day38, R.id.day39, R.id.day40, R.id.day41, R.id.day42};

    static int currentMonth = 1;
    static int currentYear = 2014;

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
    {
        super.onUpdate(context, appWidgetManager, appWidgetIds);

        for (int appWidgetId : appWidgetIds) {
            AppWidgetProviderInfo info = appWidgetManager.getAppWidgetInfo(appWidgetId);
            _sizes.recalculate(EMULATOR ? 180 : 250, EMULATOR ? 180 : 250);//info.minWidth, info.minHeight);

            drawWidget(context, appWidgetId);
        }
    }

    @Override
    public void onDisabled(Context context){
       Settings.saveSettings(context);
    }

    @Override
    public void onEnabled(Context context){
        Settings.loadSettings(context);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);

        String action = intent.getAction();

        if (ACTION_DATE_CLICK.equals(action)) {
            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
            String str = intent.getType();
            Date date = sdf.parse(str, new ParsePosition(0));
            DateDialog.date = date;

            Intent activ = new Intent(context, DateDialog.class);
            activ.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(activ);
        }
        else if (ACTION_RESET_MONTH.equals(action)) {
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
            Calendar cal = Calendar.getInstance();
            sp.edit().putInt("CurrMonth", cal.get(Calendar.MONTH))
                    .putInt("CurrYear", cal.get(Calendar.YEAR))
                    .apply();
            redrawWidgets(context);
        }
        else if (ACTION_PREVIOUS_MONTH.equals(action)) {
            Calendar cal = Calendar.getInstance();
            cal.set(currentYear, currentMonth, 1);
            cal.add(Calendar.MONTH, -1);
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
            sp.edit().putInt("CurrMonth", cal.get(Calendar.MONTH))
                    .putInt("CurrYear", cal.get(Calendar.YEAR))
                    .apply();
            redrawWidgets(context);
        }
        else if (ACTION_NEXT_MONTH.equals(action)) {
            Calendar cal = Calendar.getInstance();
            cal.set(currentYear, currentMonth, 1);
            cal.add(Calendar.MONTH, 1);
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
            sp.edit()
                    .putInt("CurrMonth", cal.get(Calendar.MONTH))
                    .putInt("CurrYear", cal.get(Calendar.YEAR))
                    .apply();
            redrawWidgets(context);
        }
        else if (ACTION_SETTINGS.equals(action)) {
            Intent activ = new Intent(context, SettingsActivity.class);
            activ.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(activ);
        }
        else if (ACTION_UPDATE.equals(action)) {
            redrawWidgets(context);
        }
    }

    private void redrawWidgets(Context context) {
        int[] appWidgetIds = AppWidgetManager.getInstance(context).getAppWidgetIds(
                new ComponentName(context, MainWindow.class));
        for (int appWidgetId : appWidgetIds) {
            _sizes.recalculate(EMULATOR ? 180 : 250, EMULATOR ? 180 : 250);
            drawWidget(context, appWidgetId);
        }
    }

    private void drawWidget(Context context, int appWidgetId) {
        Settings.loadSettings(context);
        onEnabled(context);
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

        Calendar cal = Calendar.getInstance();
        cal.setFirstDayOfWeek(Calendar.MONDAY);

        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        currentMonth = sp.getInt("CurrMonth", cal.get(Calendar.MONTH));
        currentYear = sp.getInt("CurrYear", cal.get(Calendar.YEAR));

        cal.set(currentYear, currentMonth, 1);

        Log.e("MAIN","THEME = "+Settings.theme);
        if(Settings.theme.equals("0")) _painter = new GlassPainter(_sizes);
        else if(Settings.theme.equals("1")) _painter = new ChinesePainter(_sizes);
        else if(Settings.theme.equals("2")) _painter = new TransparentPainter(_sizes);
        else if(Settings.theme.equals("3")) _painter = new TransparentBlackPainter(_sizes);
        else if(Settings.theme.equals("4")) _painter = new GreenPainter(_sizes);
        else if(Settings.theme.equals("5")) _painter = new NotepadPainter(_sizes);
        else if(Settings.theme.equals("6")) _painter = new PaperPainter(_sizes);
        else _painter = new GlassPainter(_sizes);

        RemoteViews main = new RemoteViews(context.getPackageName(), _painter.mainLayout());
        main.setImageViewBitmap(R.id.title, _painter.getBitmap(WidgetSizes.WidgetType.Title,cal,context));
        main.setImageViewBitmap(R.id.prev, _painter.getBitmap(WidgetSizes.WidgetType.Prev,cal,context));
        main.setImageViewBitmap(R.id.next, _painter.getBitmap(WidgetSizes.WidgetType.Next,cal,context));
        main.setImageViewBitmap(R.id.settings, _painter.getBitmap(WidgetSizes.WidgetType.Settings,cal,context));
        main.setImageViewBitmap(R.id.weeks, _painter.getBitmap(WidgetSizes.WidgetType.Weeks,cal,context));
        if(!Settings.theme.equals("2") && !Settings.theme.equals("3")){
            main.setImageViewBitmap(R.id.footer, _painter.getBitmap(WidgetSizes.WidgetType.Footer,cal,context));
        }
        if(Settings.theme.equals("5") || Settings.theme.equals("6")){
            main.setImageViewBitmap(R.id.leftside, _painter.getBitmap(WidgetSizes.WidgetType.LeftSide,cal,context));
            main.setImageViewBitmap(R.id.rightside, _painter.getBitmap(WidgetSizes.WidgetType.RightSide,cal,context));
        }
        if(Settings.theme.equals("6")){
            main.setImageViewBitmap(R.id.upper, _painter.getBitmap(WidgetSizes.WidgetType.Upper,cal,context));
        }

        cal.set(Calendar.DAY_OF_MONTH, 1);
        int monthStartDayOfWeek = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if(monthStartDayOfWeek == 0) monthStartDayOfWeek = 7;
        cal.add(Calendar.DAY_OF_MONTH, 1 - monthStartDayOfWeek);

        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        for(int i=0; i<42; i++){
            _painter.setDayPos(i/7, i%7);
            main.setImageViewBitmap(daysId[i], _painter.getBitmap(WidgetSizes.WidgetType.Day,cal,context));
            main.setOnClickPendingIntent(daysId[i],
                    PendingIntent.getBroadcast(context, 0,
                            new Intent(context, MainWindow.class)
                                    .setAction(ACTION_DATE_CLICK).setType(sdf.format(cal.getTime())),
                            PendingIntent.FLAG_UPDATE_CURRENT));
            cal.add(Calendar.DAY_OF_MONTH,1);
        }

        int items[] = {R.id.title, R.id.prev, R.id.next, R.id.settings};
        String actions[] = {ACTION_RESET_MONTH,ACTION_PREVIOUS_MONTH,ACTION_NEXT_MONTH,ACTION_SETTINGS};
        for(int i=0;i<4;i++){
            main.setOnClickPendingIntent(items[i],
                    PendingIntent.getBroadcast(context, 0,
                            new Intent(context, MainWindow.class)
                                    .setAction(actions[i]),
                            PendingIntent.FLAG_UPDATE_CURRENT));
        }

        appWidgetManager.updateAppWidget(appWidgetId, main);

    }


}
